package com.loong.musicdemo.ui.mine;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.loong.musicdemo.R;
import com.loong.musicdemo.model.SongList;
import com.loong.musicdemo.model.User;
import com.loong.musicdemo.ui.find.activity.ShowAlbumPlayListActivity;
import com.loong.musicdemo.ui.mine.adapter.MinePlaylistAdapter;
import com.loong.musicdemo.ui.mine.recent.RecentPlayedSongActivity;
import com.loong.musicdemo.util.dataDeal.MusicDeal;
import com.loong.musicdemo.util.dataDeal.PlayListDeal;
import com.loong.musicdemo.util.httpUtil.HttpUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class MineFragment extends Fragment {
    private ImageView user_img,bg_gif,record_song_bg;
    private TextView user_name,user_level,create_playlist_count,collect_playlist_count;
    private TextView privacy_tag,collect_tag,record_song_count;
    private List<SongList> userPlayLists = new ArrayList<>();
    private RelativeLayout love_song;
    private LinearLayout recent_record,create_playlist,collect_playlist;
    private RecyclerView create_playlist_recycler_view,collect_playlist_recycler_view;
    private List<String> recordSongIds = new ArrayList<>();
    private String likeList_bg = "";
    private User user;
    private String bgUrl = "";
    private List<SongList> privacyList = new ArrayList<>();
    private List<SongList> collectionList = new ArrayList<>();
    private MinePlaylistAdapter createPlaylistAdapter;
    private MinePlaylistAdapter collectPlaylistAdapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_mine, container, false);
        initView(root);
        initRecyclerView();
        //设置圆角图片
        Glide.with(getContext()).load(R.drawable.bg)
                .placeholder(R.drawable.temp)
                .circleCrop()
                .transform( new RoundedCorners(15))
                .skipMemoryCache(true)
                .into(bg_gif);
        bg_gif.setAlpha((float) 0.8);
        new LikeListTask().execute();
        initHandler();
        return root;
    }
    //初始化所有控件
    private void initView(View root){
        user_img = root.findViewById(R.id.user_img);
        record_song_bg = root.findViewById(R.id.record_song_bg);
        user_name = root.findViewById(R.id.user_name);
        user_level = root.findViewById(R.id.user_level);
        bg_gif = root.findViewById(R.id.bg_gif);
        love_song = root.findViewById(R.id.love_song);
        privacy_tag = root.findViewById(R.id.privacy_tag);
        collect_tag = root.findViewById(R.id.collect_tag);
        record_song_count = root.findViewById(R.id.record_song_count);
        collect_playlist = root.findViewById(R.id.collect_playlist);
        create_playlist = root.findViewById(R.id.create_playlist);
        recent_record = root.findViewById(R.id.recent_record);
        create_playlist_count = root.findViewById(R.id.create_playlist_count);
        collect_playlist_count = root.findViewById(R.id.collect_playlist_count);
        create_playlist_recycler_view = root.findViewById(R.id.create_playlist_recycler_view);
        collect_playlist_recycler_view = root.findViewById(R.id.collect_playlist_recycler_view);
    }

    /**
     * 监听事件
     */
    private void initHandler(){
        //我喜爱的歌曲点击事件
        love_song.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ShowAlbumPlayListActivity.class);
                intent.putExtra("albumName", "我喜欢的音乐");
                intent.putExtra("albumImg", bgUrl);
                intent.putExtra("albumIDs", (ArrayList)userPlayLists.get(0).getSongIds());
                intent.putExtra("albumCreatorName", user.getNickName());
                intent.putExtra("albumCreatorPic", user.getAvatarUrl());
                intent.putExtra("albumCommentCount", userPlayLists.get(0).getCommentCount());
                intent.putExtra("albumPlayCount", userPlayLists.get(0).getPlayCount());
                startActivity(intent);
            }
        });
        //最近播放的歌曲点击事件
        recent_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent recentIntent = new Intent(getContext(), RecentPlayedSongActivity.class);
                startActivity(recentIntent);
            }
        });
        //创建歌单的点击事件
        create_playlist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                create_playlist_recycler_view.setVisibility(View.VISIBLE);
                collect_playlist_recycler_view.setVisibility(View.GONE);
                privacy_tag.setTextColor(getResources().getColor(R.color.tag_selected));
                create_playlist_count.setTextColor(getResources().getColor(R.color.tag_selected));
                collect_tag.setTextColor(getResources().getColor(R.color.tag_unselected));
                collect_playlist_count.setTextColor(getResources().getColor(R.color.tag_unselected));
            }
        });
        //收藏歌单的点击事件
        collect_playlist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                create_playlist_recycler_view.setVisibility(View.GONE);
                collect_playlist_recycler_view.setVisibility(View.VISIBLE);
                collect_tag.setTextColor(getResources().getColor(R.color.tag_selected));
                collect_playlist_count.setTextColor(getResources().getColor(R.color.tag_selected));
                privacy_tag.setTextColor(getResources().getColor(R.color.tag_unselected));
                create_playlist_count.setTextColor(getResources().getColor(R.color.tag_unselected));
            }
        });
    }

    private void initRecyclerView(){
        //设置当前用户的创建歌单
        StaggeredGridLayoutManager createManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        createPlaylistAdapter = new MinePlaylistAdapter(privacyList,getContext());
        create_playlist_recycler_view.setLayoutManager(createManager);
        create_playlist_recycler_view.setAdapter(createPlaylistAdapter);
        //设置当前用户的收藏歌单
        StaggeredGridLayoutManager collectManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        collectPlaylistAdapter = new MinePlaylistAdapter(collectionList,getContext());
        collect_playlist_recycler_view.setLayoutManager(collectManager);
        collect_playlist_recycler_view.setAdapter(collectPlaylistAdapter);
    }


    class LikeListTask extends AsyncTask<User,Void,User>{
        @Override
        protected void onPostExecute(User user) {
            super.onPostExecute(user);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.temp);
            requestOptions.circleCropTransform();
            requestOptions.bitmapTransform(new RoundedCorners(10));
            //设置用户信息
            if(getContext()!=null){
                Glide.with(getContext()).load(user.getAvatarUrl()).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).into(user_img);
                Glide.with(getContext()).load(likeList_bg).apply(requestOptions).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).into(record_song_bg);
            }
            user_name.setText(user.getNickName());
            user_level.setText("lv" + "  " + user.getLevel());
            //更新对应的列表
            privacyList.addAll(getUserPrivacyPlaylist(userPlayLists));
            collectionList.addAll(getUserCollectionPlaylist(userPlayLists));
            createPlaylistAdapter.notifyDataSetChanged();
            collectPlaylistAdapter.notifyDataSetChanged();

            create_playlist_count.setText(String.valueOf(privacyList.size()));
            collect_playlist_count.setText(String.valueOf(collectionList.size()));
            record_song_count.setText(String.format("%s首", String.valueOf(recordSongIds.size())));
        }

        @Override
        protected User doInBackground(User... u) {
            SharedPreferences userInfo = getContext().getSharedPreferences("userInfo",MODE_PRIVATE);
            String userId = userInfo.getString("userId", null);
            //获取用户所有的歌单列表
            userPlayLists = PlayListDeal.getUserAllPlayListInfo(userId);
            //获取用户最近播放音乐的id
            recordSongIds = MusicDeal.getWeekPlayRecordIds(userId);
            user = new User();
            user.setUserId(userId);
            String responseBody = HttpUtil.sendReturnOKHttpRequest(getResources().getString(R.string.host)+"/user/detail?uid="+userId);
            try {
                if (responseBody != null) {
                    JSONObject object = new JSONObject(responseBody);
                    user.setLevel(object.getInt("level"));
                    user.setListenSongs(object.getInt("listenSongs"));
                    JSONObject profile = object.getJSONObject("profile");
                    user.setNickName(profile.getString("nickname"));
                    user.setAvatarUrl(profile.getString("avatarUrl"));
                    bgUrl = profile.getString("backgroundUrl");
                    //获取最近播放音乐中第一个音乐的id的图片地址
                    likeList_bg = MusicDeal.getMusicPicUrl(recordSongIds.get(0));
                    return user;
                } else return null;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


    /**
     * 获取所有歌单中的自建歌单
     * @param userPlayLists 用户所有的歌单
     * @return 自建歌单
     */
    private List<SongList> getUserPrivacyPlaylist(List<SongList> userPlayLists){
        List<SongList> privacyPlaylist = new ArrayList<>();
        //下标从一开始，因为下标为零的是用户喜欢的音乐
        for(int i = 1;i<userPlayLists.size();i++){
            if(userPlayLists.get(i).getCreatorId().equals(user.getUserId())){
                privacyPlaylist.add(userPlayLists.get(i));
            }
        }
        return privacyPlaylist;
    }

    /**
     * 获取所有歌单中的收藏歌单
     * @param userPlayLists 用户所有的歌单
     * @return 收藏歌单
     */
    private List<SongList> getUserCollectionPlaylist(List<SongList> userPlayLists){
        List<SongList> collectionPlaylist = new ArrayList<>();
        //下标从一开始，因为下标为零的是用户喜欢的音乐
        for(int i = 1;i<userPlayLists.size();i++){
            if(!userPlayLists.get(i).getCreatorId().equals(user.getUserId())){
                collectionPlaylist.add(userPlayLists.get(i));
            }
        }
        return collectionPlaylist;
    }


}
